/* 
 * Nome do Projeto: CPE
 * Nome da Classe : ExceptionHandlingListener.java
 * Data de Criação: 21/07/2009
 * 
 * 
 * HISTÓRICO DE MUDANÇAS:
 * =====================================================================
 * ####        Mozart Silva
 * 21/07/2009  Versão Inicial
 * =====================================================================
 */
package br.iars.web.listener;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.sun.faces.application.ActionListenerImpl;

/**
 * Listener para tratamento de exceção.
 * 
 * @author Jefferson Silva de Amorim
 * 
 */
public class ExceptionHandler extends ActionListenerImpl implements ActionListener {
	
    /** {@inheritDoc} */
    public void processAction(ActionEvent event) {
        try {
            super.processAction(event);
        } catch (Throwable t) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter, true);
            t.printStackTrace(printWriter);
            printWriter.flush();
            stringWriter.flush();
            String message = stringWriter.toString();

            FacesContext facesContext = FacesContext.getCurrentInstance();
			try {
				((HttpSession) facesContext.getExternalContext().getSession(false)).setAttribute("errorMessage", message);
				facesContext.getExternalContext().redirect("error.xhtml");
			} catch (IOException e) {
				Logger.getLogger(this.getClass()).error(e.getMessage(), e);
				e.printStackTrace();
			}
        }
    }
}
